package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端程序:
 */
public class Server {
    private ServerSocket serverSocket;
    public Server() {
        try {
            System.out.println("正在启动服务端>>>");
            serverSocket = new ServerSocket(8091);
            System.out.println("服务端启动成功!!!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        try {
            System.out.println("正在等待客户端接入>>>");
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功!!!");
            ClientHander cl = new ClientHander(socket);
            Thread t = new Thread(cl);
            t.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
    private class ClientHander implements Runnable{
        private String host;
        private Socket socket;
        public ClientHander(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,"UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine())!=null){
                    System.out.println(host+"说:"+line);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
